/*
	This file is part of SRServerLibrary.
	Foobar is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	SRServerLibrary is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with SRServerLibrary.  If not, see <http://www.gnu.org/licenses/>.
*/


#include "SRNetworkServer.h"
#include <QDebug>
#include <QDataStream>
#include <QByteArray>



using namespace std;


SRNetworkServer::SRNetworkServer(SRSettings *s, SRMessenger *m)
{
	settings = s;
	messenger = m;

	// connect signals and slots
	QObject::connect(&server, SIGNAL(newConnection()), this, SLOT(clientConnected()));


	this->startListening();
}

void SRNetworkServer::startListening()
{
	server.listen(QHostAddress::Any, settings->getPort());
	qDebug() << "TCP server listening on port " << settings->getPort();
}


void SRNetworkServer::stopListening()
{
	server.close();
}


void SRNetworkServer::sendMessage(SRCommand command)
{
	
}


void SRNetworkServer::broadcast(SRCommand command)
{
	
}


// ---- private signals ----


void SRNetworkServer::clientConnected()
{
	qDebug() << "incoming TCP connection";
	if(server.hasPendingConnections())
	{
		qDebug() << "setting up socket";

		QTcpSocket *newSocket = server.nextPendingConnection();

		// add socket to list of sockets
		connections += newSocket;

		// connect signals and slots for the socket
		QObject::connect(newSocket, SIGNAL(readyRead()), this, SLOT(receiveMessage()));
	}
}


void SRNetworkServer::receiveMessage()
{
	QTcpSocket *sender = (QTcpSocket*)QObject::sender();

	QString message = sender->readLine();

	SRCommandList response;

	qDebug() << "received message " << message;

	// remove possible appended witespace
	message = message.trimmed();


	if(SRCommand::isCommand(message))
	{
		qDebug() << "broadcasting command";
		response = messenger->internalBroadcast(SRCommand(message));
	}
	else if(SRCommandList::isCommandList(message))
	{
		qDebug() << "broadcasting command list";
		response = messenger->internalBroadcast(SRCommandList(message));
	}

	qDebug() << "Response: " << response.toString();
	qDebug() << "count: " << response.size();

	// send response to client
	sender->write(response.toString().toAscii());
	qDebug() << "sending response";
	qDebug() << sender->errorString();


	//qDebug() << "Response: " << response.toString();

	/*
	if(sender->waitForBytesWritten()==false)
	{
		qDebug() << "ERROR: Could not send response";
	}
	else
	{
		qDebug() << "Response sent to client";
	}*/
}

